import { ResponseState } from '@CONSTANTS/BleConstants'
import BluUtils from '@UTILS/BluUtils'
import { DeviceInfoBleResponse, DeviceResponse } from '@TYPES/BleTypes'

class DeviceResponseParser {
  private static getResponseCode=(tokens: Array<string>) => {
    const responseCodeString = tokens[1]
    const responseCodeInt = parseInt(responseCodeString || '-1', 16)
    return { codeInt: responseCodeInt, code: BluUtils.toResponseCode(responseCodeInt) }
  }

  private static getDeviceState=(tokens: Array<string>) => {
    const deviceStateString = tokens[3]
    const responseCodeInt = parseInt(deviceStateString || '0', 10)
    return { deviceStateInt: responseCodeInt, deviceState: BluUtils.toDeviceState(responseCodeInt) }
  }

  private static parseTokens = (tokens: Array<string>): DeviceResponse => {
    console.log('tokenstokens', tokens)
    const code = this.getResponseCode(tokens)
    const command = tokens[2]
    const deviceState = this.getDeviceState(tokens)
    return {
      ...code, ...deviceState, command, responseStatus: tokens[0].toLowerCase() as ResponseState,
    } as DeviceResponse
  }

  static parse(data?: string | null) {
    const trimmedString = data?.substr(0, data?.lastIndexOf(String.fromCharCode(0)))
    console.log('DeviceResponseParser: parse', `${trimmedString}`, String.fromCharCode(0))
    const tokens = trimmedString?.split(' ')
    if (!tokens || tokens.length === 0) {
      return {} as DeviceResponse
    }
    const parseTokensData = this.parseTokens(tokens)
    console.log('parseTokensData', parseTokensData)
    return parseTokensData
  }

  static parseSerialNumber(data?: string | null) {
    const trimmedString = data?.substr(0, data?.lastIndexOf(String.fromCharCode(0)))
    console.log('DeviceResponseParser: parseSerialNumber', trimmedString, trimmedString?.replace(/^(UDI:)/gi, '').trim())
    return trimmedString?.replace(/^(UDI:)/gi, '').trim()
  }

  static parseDeviceInfo(data?: string | null): DeviceInfoBleResponse {
    const tokens = data?.split(' ')
    if (!tokens || tokens.length === 0) {
      return { pauseDefaultTimeInSeconds: 5 * 60, isError: true } as DeviceInfoBleResponse
    }
    const trimmedString = data?.substr(0, data?.lastIndexOf(String.fromCharCode(0)))
    console.log('DeviceResponseParser: parseDeviceInfo', trimmedString)
    const fwVersion = tokens[1]
    const hwRevision = tokens[2]
    const treatmentDefaultTimeInSeconds = Number(tokens[3]) * 60
    const minTreatmentTimeInSeconds = Number(tokens[4]) * 60
    const lockStatus = tokens[5]
    const bleAddress = tokens[6]
    const bootVersion = tokens[7]
    return {
      pauseDefaultTimeInSeconds: 5 * 60,
      fwVersion,
      hwRevision,
      treatmentDefaultTimeInSeconds,
      minTreatmentTimeInSeconds,
      lockStatus,
      bleAddress,
      bootVersion,
    }
  }
}

export default DeviceResponseParser
